package com.example.springdemo5;

import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/main1")
public class Main1 {
    @RequestMapping("/getCookie1")
    public String getCookie1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        StringBuilder stringBuilder = new StringBuilder();
        //判断 cookies 是否为空
        if(cookies != null) {
            for(Cookie cookie : cookies) {
                stringBuilder.append(cookie.getName() + ":" + cookie.getValue() );
            }
            return stringBuilder.toString();
        }
        return "Cookie 为空";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("cookie1") String cookie) {
        return "cookie:" + cookie;
    }

    //设置Session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("username","张三");
        return "session设置成功";
    }

    @RequestMapping("/getSession1")
    public String getSession1(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session != null) {
            String username = (String) session.getAttribute("username");
            return "username:" + username;
        }
        return "session为空";
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        String username = (String)session.getAttribute("username");
        return "username:" + username;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute(value = "username", required = false) String username) {
        return "username:" + username;
    }


}
